﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection.Emit;

namespace Slam.Internal
{
	public static class TypeExtensions
	{
		public static T CreateInstance<T>(this Type type) where T : class
		{
			var target = type.GetConstructor(Type.EmptyTypes);
			var dynamic = new DynamicMethod(string.Empty,
						  type,
						  new Type[0],
						  target.DeclaringType);
			var il = dynamic.GetILGenerator();
			il.DeclareLocal(target.DeclaringType);
			il.Emit(OpCodes.Newobj, target);
			il.Emit(OpCodes.Stloc_0);
			il.Emit(OpCodes.Ldloc_0);
			il.Emit(OpCodes.Ret);

			var method = (Func<T>)dynamic.CreateDelegate(typeof(Func<T>));
			return method();
		}
	}
}
